<?php

// +----------------------------------------------------------------------
// | OneChat
// +----------------------------------------------------------------------
// | Copyright (c) 2014 http://www.tealun.com
// +----------------------------------------------------------------------
// | Author: Tealun Du <tealun@tealun.com> <http://www.tealun.com>
// +----------------------------------------------------------------------

namespace Admin\Controller;

use Wechat\Api\Api;
use Wechat\Api\MenuApi;
use Wechat\Api\TagsApi;
/**
 * 自定义菜单管理控制器

 */
class WechatMenuController extends WechatController {

    protected $WechatMenu = NULL;

    protected function _initialize() {
        $this->WechatMenu = new MenuApi();
        parent::_initialize();
    }

    /**
     * 查看个性化菜单列表
     * 查看现有服务器上的目录
     */
    public function menuList() {

       $list = D('TchatMenuList')->select();

        //替换标识名称
        $list=$this->replaceNames($list);

        $this->assign('_list',$list);

        $this->assign('meta_title' , '查看自定义菜单列表');
        $this->display();
    }

    /**
     * 新增个性化菜单列表
     */
    public function addMenuList(){
        //获取关键词分组模型
        $model = M('Model')->where(array( 'id' => 53 ))->find();
        $info['model_id'] = '53';
        //获取表单字段排序
        $fields = get_model_attribute($model['id']);
        $this->assign('info' , $info);
        $this->assign('fields' , $fields);
        $this->assign('model' , $model);

        $this->display();
    }

    /**
     * 编辑个性化菜单列表
     *
     * @param $menuId 个性化菜单ID
     */
    public function editMenuList(){
        //获取关键词分组模型
        $id = I('get.id');
        $model = M('Model')->where(array( 'id' => 53 ))->find();
        $data = D('Tchat_menu_list')->info($id);
        $info['model_id'] = '53';
        $info['id'] = $id;
        //获取表单字段排序
        $fields = get_model_attribute($model['id']);
        $this->assign('info' , $info);
        $this->assign('data' , $data);
        $this->assign('fields' ,$fields);
        $this->assign('model' , $model);
        $this->meta_title = '编辑个性化菜单';
        $this->display();
    }

    /**
     * 删除个性化菜单
     */
    public function delMenuList(){
        $MenuList = D('Tchat_menu_list');

        /* 批量删除 */
        if(IS_POST||IS_AJAX){
            $menuIds = I('post.menuids');
            foreach($menuIds as $menuid){
                 $re = $MenuList->delete($menuid);
                 if(false == $re){
                     $this->error('删除编号'.$menuid.'时候出现错误！');
                     exit;
                 }
            }
            $this->success('批量删除成功！');

        /* 单个删除 */
        }else{
            $menuid = I('get.menuid');
            $re = $MenuList->delete($menuid);
            if(false == $re){
                $this->error('删除编号'.$menuid.'时候出现错误！');
            }else{
                $this->success('删除成功！');
            }
        }

    }

    public function updateMenuList() {
        $TchatMenuList = D('Tchat_menu_list');
        if ( IS_POST ) {
            $re = $TchatMenuList->update();
            if ( false !== $re && 0 !== $re ) {
                    $this->success('操作成功！' , U('menuList'));
            } else {
                $error = $TchatMenuList->getError();
                $this->error(empty( $error ) ? '未知错误！' : $error);
            }
        }
    }

    /**
     * 发布个性化菜单
     */
    public function publishMenuList(){

        $MenuList = D('Tchat_menu_list');
        $ids = I('post.ids');
        $id = I('get.id');

        //批量发布用POST
        if(IS_POST||IS_AJAX){
            if(!empty($ids)){
                foreach($ids as $id){
                    $tree = D('Tchat_menu')->getTree($id ,0, 'id,pid,menu_type,name,event_key,url');
                    //清理掉$tree中用于排序和分级而获取到的字段，这些字段不需要发送到服务器
                    $data['button'] = $this->clearTreeArr($tree);
                    $re = $MenuList->publish($id,$data);
                    if($re['errcode'] != 0){
                        $this->error('发布编号'.$id.'时候出现错误！错误信息：'.$re['errmsg']);
                        exit;
                    }
                }
                $this->success('批量发布成功！');
            }
        }
        //单个发布用GET
        if($id){
            $tree = D('Tchat_menu')->getTree($id ,0, 'id,pid,menu_type,name,event_key,url');
            //清理掉$tree中用于排序和分级而获取到的字段，这些字段不需要发送到服务器
            $data['button'] = $this->clearTreeArr($tree);
            $re = $MenuList->publish($id,$data);
            if($re['errcode'] !== 0){
                $this->error('发布编号'.$id.'时候出现错误！错误信息：'.$re['errmsg']);
            }else{
                $this->success('发布成功！');
            }
        }

    }

    /**
     * 查看菜单
     * 查看现有服务器上的目录
     */
    public function viewMenu() {
        if(I('get.id')){
            $info = D('TchatMenuList')->info(I('get.id'),'id,title,tag_id,sex,country,province,city,client_platform_type,language,status');
            $info = $this->replaceNames(array($info));
            $info = $info[0];
            $menuid = $info['id'];
            $this->assign('meta_title' , '查看个性化菜单['.$info['title'].']');
            $this->assign('info',$info);
        }else{
            $menuid = 0;
            $this->assign('meta_title' , '查看自定义菜单[默认]');
        }
        $menuid = 0;
        $tree = D('Tchat_menu')->getTree($menuid,0 , 'id,sort,name,pid,status');
         $this->assign('tree' , $tree);
        C('_TCHAT_GET_MENU_TREE_' , true);
         $this->display();
    }

    /**
     * 显示菜单树，仅支持内部调
     *
     * @param  array $tree 菜单树
     *
     * @author 麦当苗儿 <zuojiazi@vip.qq.com>
     */
    public function tree($tree = NULL) {
        C('_TCHAT_GET_MENU_TREE_') || $this->_empty();
        $this->assign('tree' , $tree);
        $this->display('tree');
    }

    /**
     * 编辑自定义菜单
     *
     * @param int $id  菜单条目的ID
     * @param int $pid 菜单条目的上级菜单ID
     */
    public function edit() {

        $id = I('get.id' , '');
        if ( empty( $id ) ) {
            $this->error('参数不能为空！');
        }

        /*获取一条记录的详细数据*/
        $TchatMenu = D('Tchat_menu');
        $data = $TchatMenu->info($id);
        if ( !$data ) {
            $this->error($TchatMenu->getError());
        }
        //赋值data变量，将作为字段的已有数据值对应设置为字段值
        $this->assign('data' , $data);

        $info['model_id'] = '52';
        $info['id'] = $id;

        //获取菜单模型
        $model = M('Model')->where(array( 'id' => $info['model_id'] ))->find();

        //获取表单字段排序
        $fields = get_model_attribute($model['id']);
        //获取回复模版
        $fields = parent::getReplyFlow($fields);

        $this->assign('info' , $info);
        $this->assign('fields' , $fields);
        $this->assign('model' , $model);

        //如果该菜单PID大于0，判断上级菜单的状态并且获取相关信息
        if ( $data['pid'] > 0) {
            /* 获取上级菜单信息 */
            $pidInfo = $TchatMenu->info($data['pid'] , 'id,menuid,name,status');

            if ( !( $pidInfo && 1 == $pidInfo['status'] ) ) {
                $this->error('指定的上级菜单不存在或被禁用！');
            }

            //pid为0，则为一级菜单
        }else{
            $pidInfo = array(
                'id'=> 0,
                'name'=>''
            );
        }

        if($data['menuid'] == 0){
            $pidInfo['menuid'] = 0;
            $pidInfo['menuListTitle'] = "微信默认菜单";
        }else{
            $pidInfo['menuid'] = $data['menuid'];
            $pidInfo['menuListTitle'] = M('TchatMenuList')->where('`id` =' .$pidInfo['menuid'])->getField('title');
        }

        //赋值上级菜单信息,这个变量要以JSON格式发送到页面的JAVASCRIPT脚本使用
        $pidInfo = JSON($pidInfo);
        $this->assign('pidInfo' , $pidInfo);

        $this->meta_title="编辑菜单细项";
        $this->display('add');

    }

    /**
     * 新增自定义菜单
     *
     * @param  int $pid 新增菜单的上级菜单ID
     */
    public function add() {

        $TchatMenu = D('Tchat_menu');
        $info['model_id'] = '52';
        $pid = I('get.pid')?I('get.pid'):0;
        /* 新增菜单页面的变量赋值 */

        //获取菜单模型
        $model = M('Model')->where(array( 'id' => $info['model_id'] ))->find();

        //获取表单字段排序
        $fields = get_model_attribute($model['id']);
        //获取回复模版
        $fields = parent::getReplyFlow($fields);

        $this->assign('info' , $info);
        $this->assign('fields' , $fields);
        $this->assign('model' , $model);

        /* 设置上级菜单选项 */
        //如果有传入上级菜单ID，判断上级菜单的状态并且获取相关信息
        if ( $pid ) {
            /* 获取上级菜单信息 */
            $pidInfo = $TchatMenu->info($pid , 'id,menuid,name,menu_type,pid,status');
            if($pidInfo['pid'] == 0 && $pidInfo['menu_type'] != 'button'){
                $this->error('请重新设置该菜单的类型为“一级菜单”后再添加子菜单。',U('edit',array('id'=>$pid)));
            }
            if ( !( $pidInfo && 1 == $pidInfo['status'] ) ) {
                $this->error('指定的上级菜单不存在或被禁用！');
            }else{
                //判断上级菜单所属菜单类型
                if($pidInfo['menuid'] == 0){
                    $pidInfo['menuListTitle'] = "微信默认菜单";
                }else{
                    $pidInfo['menuListTitle'] = M('TchatMenuList')->where('`id` =' .$pidInfo['menuid'])->getField('title');
                }
            }

        //没有传入或pid为0，则为增加一级菜单
        }else{
            $pidInfo = array(
                'id'=> 0,
                'name'=>''
            );
            //赋值所属菜单类型
            if(I('get.menuListId')){
                $pidInfo['menuid'] = I('get.menuListId');
                $pidInfo['menuListTitle'] = M('TchatMenuList')->where('`id` =' .$pidInfo['menuid'])->getField('title');
            }else{
                $pidInfo['menuid'] = 0;
                $pidInfo['menuListTitle'] = "微信默认菜单";
            }
        }



        //赋值上级菜单信息,这个变量要以JSON格式发送到页面的JAVASCRIPT脚本使用
        $pidInfo = JSON($pidInfo);
        $this->assign('pidInfo' , $pidInfo);

        /* 获取菜单信息 */
        $this->meta_title = '新增菜单细项';
        $this->display();

    }

    /**
     * 新增或更新数据
     */
    public function update() {

        $TchatMenu = D('Tchat_menu');
        if ( IS_POST ) {
            $id = I('post.id');
            $menuid = I('post.menuid');
            if ( false !== $TchatMenu->update() ) {

                if ( !empty( $id ) ) {
                    $this->success('更新成功！' , U('viewMenu',array('id'=>$menuid)));
                } else {
                    $this->success('新增成功！' , U('viewMenu',array('id'=>$menuid)));
                }
            } else {
                $error = $TchatMenu->getError();
                $this->error(empty( $error ) ? '未知错误！' : $error);
            }
        }

    }

    /**
     * 删除一个菜单项
     * @author huajie <banhuajie@163.com>
     */
    public function remove() {
        $menu_id = I('id');
        if ( empty( $menu_id ) ) {
            $this->error('参数错误!');
        }

        //判断该菜单下有没有子菜单，有则不允许删除
        $child = M('Tchat_menu')->where(array( 'pid' => $menu_id ))->field('id')->select();
        if ( !empty( $child ) ) {
            $this->error('请先删除该菜单下的子菜单');
        }

        //删除该菜单信息
        $res = M('Tchat_menu')->delete($menu_id);
        if ( $res !== false ) {
            //记录行为
            action_log('delete_tchat_menu' , 'tchatMenu' , $menu_id , UID);
            $this->success('删除菜单成功！');
        } else {
            $this->error('删除菜单失败！');
        }
    }

    /**
     * 更改状态
     * TODO 对目录条目状态进行操作
     * @see Application/Admin/Controller/AdminController::setStatus()
     */
    public function setStatus($model = 'TchatMenu') {
        return parent::setStatus($model);
    }


    /**
     * 生成菜单到微信服务器
     *
     * @param  string $data 菜单的array
     *
     * @return string  返回的结果；
     */
    public function setMenu() {
        if ( IS_POST ) {

            $menuid = 0;
            $tree = D('Tchat_menu')->getTree($menuid ,0, 'id,pid,menu_type,name,event_key,appid,page_path,url');

            //清理掉$tree中用于排序和分级而获取到的字段，这些字段不需要发送到服务器
            $menu['button'] = $this->clearTreeArr($tree);

            $res = set_wechat_menu($menu);

            if ( $res['errcode'] == 0 ) {
                S('menuLocalChange' , NULL); //清除本地数据状态更改标识
                F('defaultMenuSet','published');//设置默认菜单已发布到服务器
                $this->success('发布成功！');
            } elseif ( $res['errcode'] == 40001 ) {//针对accessToken错误重置一次accessToken
                get_access_token(true);
                $this->error('抱歉，发布失败，已重置 AccessToken，请重试一次');
            } else {

                $this->error('抱歉，发布失败！' . $res['errmsg']);
            }

        } else {
            $this->error('非法操作！');
        }

    }

    /**
     * 查询微信服务器菜单
     * TODO 后期在菜单管理中加入从服务器导入功能
     * @return string  返回的结果；
     */
    private function getMenu() {

    }

    /**
     * 将获取到的目录树整理成为符合微信目录JSON数据的结构
     */
    private function clearTreeArr($arr) {
        if ( is_array($arr) ) {
            foreach ( $arr as $key => $value ) {

                //删除不必要的ID PID选项
                unset( $arr[$key]['id'] , $arr[$key]['pid'] );

                //TYPE赋值删除TYPE键位和键值
                $arr[$key]['type'] = $arr[$key]['menu_type'];
                unset( $arr[$key]['menu_type'] );

                //如果键值为空的字段，则直接去掉
                if ( empty( $arr[$key]['event_key'] ) ) {
                    unset( $arr[$key]['event_key'] );
                } else {
                    $arr[$key]['key'] = $arr[$key]['event_key'];
                    unset( $arr[$key]['event_key'] );
                }

                if ( empty( $arr[$key]['appid'] ) ){
                    unset( $arr[$key]['appid'] );
                }

                if ( !empty( $arr[$key]['page_path'] ) ){
                    $arr[$key]['pagepath'] = $arr[$key]['page_path'];
                }
                unset( $arr[$key]['page_path'] );

                if ( empty( $arr[$key]['url'] ) ){
                    unset( $arr[$key]['url'] );
                }


                //判断是否有二级菜单，有则再进行一次自身遍历
                if ( is_array($arr[$key]['_']) ) {

                    //将目录树里的二级键位替换为sub_button，并清空原键位数据
                    $arr[$key]['sub_button'] = $this->clearTreeArr($arr[$key]['_']);
                    unset( $arr[$key]['_'] );
                }
            }
        }

        return $arr;
    }

    /**
     * 删除微信服务器菜单
     * @return string  返回的结果；
     */
    private function deleteMenu($menuid) {

        if($menuid > 0){
           $re = del_conditional_menu($menuid);
        }else{
            $re = del_wechat_menu();
        }

        if(true !== $re){
            $this->error($re['errmsg']);
        }else{
            $msg = $menuid > 0 ? '删除微信服务器个性化菜单成功'.$menuid:'清空微信服务器自定义菜单（含所有个性化菜单）成功';
            $this->success($msg);
        }

    }

    /**
     * 替换个性化菜单列表中适用的标签
     *
     * @param $list
     */
    private function replaceNames($list){

        $Tag = new TagsApi();
        $tags = $Tag->getTags();//获取服务器tags

        foreach($list as $key => $value){//遍历个性化菜单列表

            /* 替换发布状态 */
            $list[$key]['status']= $value['status']?'已发布':"未发布";

            /* 替换适用标签名称 */
            if($value['tag_id'] > 0 ){//判断个性化菜单中的标签值是否设置
                foreach($tags as $k => $v){//遍历获得的Tags
                    if($v['id'] == $value['tag_id']){//找到对应的tagid
                        $list[$key]['tag_id'] = $v['name'];//将tag_id转换成标签名称
                    }
                }
            }else{//如果没有设置适用标签
                $list[$key]['tag_id'] = '';
            }

            /* 替换适用性别名称 */
            switch($value['sex']){
                case '1':
                    $list[$key]['sex'] = '男';
                    break;
                case '2':
                    $list[$key]['sex'] = '女';
                    break;
                default:
                    $list[$key]['sex'] = '';
            }

            /* 替换适用手机系统名称 */
            switch($value['client_platform_type']){
                case '1':
                    $list[$key]['client_platform_type'] = '苹果系统';
                    break;
                case '2':
                    $list[$key]['client_platform_type'] = '安卓系统';
                    break;
                case '3':
                    $list[$key]['client_platform_type'] = '其他系统';
                    break;
                default:
                    $list[$key]['client_platform_type'] = '';
            }

            /* 替换适用语言名称 */
            switch($value['language']){
                case 'zh_CN':
                    $list[$key]['language'] = '简体中文';
                    break;
                case 'zh_TW':
                    $list[$key]['language'] = '繁体中文(台湾)';
                    break;
                case 'zh_HK':
                    $list[$key]['language'] = '繁体中文(香港)';
                    break;
                case 'en':
                    $list[$key]['language'] = '英文';
                    break;
                case 'id':
                    $list[$key]['language'] = '印度尼西亚';
                    break;
                case 'ms':
                    $list[$key]['language'] = '马来西亚';
                    break;
                case 'es':
                    $list[$key]['language'] = '西班牙';
                    break;
                case 'ko':
                    $list[$key]['language'] = '韩国';
                    break;
                case 'it':
                    $list[$key]['language'] = '意大利';
                    break;
                case 'ja':
                    $list[$key]['language'] = '日本';
                    break;
                case 'pl':
                    $list[$key]['language'] = '波兰';
                    break;
                case 'pt':
                    $list[$key]['language'] = '葡萄牙';
                    break;
                case 'ru':
                    $list[$key]['language'] = '俄国';
                    break;
                case 'th':
                    $list[$key]['language'] = '泰文';
                    break;
                case 'vi':
                    $list[$key]['language'] = '越南';
                    break;
                case 'ar':
                    $list[$key]['language'] = '阿拉伯语';
                    break;
                case 'hi':
                    $list[$key]['language'] = '北印度';
                    break;
                case 'he':
                    $list[$key]['language'] = '希伯来';
                    break;
                case 'tr':
                    $list[$key]['language'] = '土耳其';
                    break;
                case 'de':
                    $list[$key]['language'] = '德语';
                    break;
                case 'fr':
                    $list[$key]['language'] = '法语';
                    break;
                default:
                    $list[$key]['language'] = '';
            }

        }

        return $list;
    }

}
